import Cookie from 'js-cookie'
import { Router } from 'vue-router';

interface State {
  isCollapse: boolean,
  tabList: TableObject[],
  currentMenu: TableObject,
  menu: Array<Object>
}
interface TableObject {
  path: string,
  name: string,
  meta: { title: string, icon: string }
}

const components = {
  Home: "../../views/home/index.vue",
  User: "../../views/user/index.vue",
  Room: "../../views/room/index.vue",
  Device: "../../views/device/index.vue",
  Hard: "../../views/device/hard.vue",
  Soft: "../../views/device/soft.vue"
}

export default {
  state: {
    isCollapse: false,
    tabList: [
      {
        path: '/',
        name: 'Home',
        meta: { title: '首页', icon: 'house' }
      }
    ],
    currentMenu: null,
    menu: []
  },
  mutations: {
    CHANGETAB(state: State) {
      state.isCollapse = !state.isCollapse;
    },
    SELECTMENU(state: State, value: TableObject) {
      if (value.name !== 'Index') {
        state.currentMenu = value;
        const result = state.tabList.findIndex(item => item.name === value.name);
        if (result === -1) {
          state.tabList.push(value);
        } else {
          state.currentMenu = null as unknown as TableObject;
        }
      }
    },
    CLOSETAG(state: State, name: string) {
      const index = state.tabList.findIndex(item => item.name === name);
      state.tabList.splice(index, 1);
    },
    SETMENU(state: State, val: Array<Object>) {
      state.menu = val;
      Cookie.set('menu', JSON.stringify(val));
    },
    CLEARMENU(state: State) {
      state.menu = [];
      Cookie.remove('menu');
    },
    ADDROUTER(state: State, router: Router) {
      if (!Cookie.get('menu')) {
        return;
      }
      const menu = JSON.parse(Cookie.get('menu'))
      state.menu = menu;
      router.addRoute('Index', {
        path: '',
        name: "Home",
        component: () => import(components['Home'])
      })
      menu.forEach(ele => {
        if (ele.name === 'Index') return;
        if (ele.children) {
          ele.children.forEach(ch => {
            ch.path = ch.name.toLowerCase();
            ch.component = () => import(components[ch.name]);
            // router.addRoute(ele.name, ch);  // 嵌套路由只需要确定项就可以了，父路由的 addRoute 会一起添加
          })
        }
        ele.path = ele.name.toLowerCase();
        ele.component = () => import(components[ele.name]);
        router.addRoute('Index', ele);
      })
    }
  }
}